#ifndef __SINGLETON_H__
#define __SINGLETON_H__

#include <pthread.h>

static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;

template <class Type>
class Singleton {

public:
    static Type *Instance();

private:
    Singleton() {
        ptr_ = NULL;
    }

    ~Singleton() {
        if (ptr_) {
            delete ptr_;
        }
    }

private:
    Type *ptr_;
};

template <class Type>
Type *Singleton::instance() {
    if (ptr_ == NULL) {
        pthread_mutex_lock(&g_mutex);
        if (ptr_ == NULL) {
            ptr_ = new Type;
        }
        pthread_mutex_unlock(&g_mutex);
    }
    
    return ptr_;
}

#endif

